package bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;
import java.util.Locale;
import java.util.Map;

public class Person implements ApplicationContextAware, BeanNameAware,
        InitializingBean, DisposableBean{
    private List<String> schools;
    private Map scores;
    private Axe axe;
    private ApplicationContext applicationContext;
    private String beanName;

    public Person() {
        System.out.println("Person的无参数构造器");
    }

    public Person(Axe axe) {
        System.out.println("Person的有参数构造器");
        this.axe = axe;
    }

    public void setAxe(Axe axe) {
        System.out.println("SetAxe方法执行");
        this.axe = axe;
    }

    public Axe getAxe() {
        return axe;
    }

    //实现ApplicationContextAware接口，Spring会调用set方法，注入applicationContext
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
        System.out.println("===setApplicationContext===");
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //在bean类中获取所在的spring容器
    public void sayHi(){
        System.out.println(
                applicationContext.getMessage("hello",
                        new String[]{"person"},
                        Locale.getDefault())
        );
    }

    public List<String> getSchools() {
        return schools;
    }

    public void setSchools(List<String> schools) {
        this.schools = schools;
    }

    public Map getScores() {
        return scores;
    }

    public void setScores(Map scores) {
        this.scores = scores;
    }

    //实现BeanNameAware接口
    @Override
    public void setBeanName(String s) {
        this.beanName = s;
        System.out.println("===setBeanName===");
    }
    public void info(){
        System.out.println("Person指定的id为: "+beanName);
    }

    //实现InitializingBean接口，在实例化结束后调用此方法；
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("正在执行初始化方法afterPropertiesSet...");
    }
    //测试配置initial-method属性的方法
    public void init(){
        System.out.println("正在执行初始化方法init...");
    }

    //实现DisposableBean接口，在被销毁钱调用
    @Override
    public void destroy() throws Exception {
        System.out.println("正在执行destroy方法...");
    }
    //测试配置destroy-method
    public void close(){
        System.out.println("正在执行close方法...");
    }
}
